
# Import
import os
import sys
import codecs

def extractDir(path):
    dir = os.path.dirname(path)
    if dir == "":
        return "."
    return dir

def removeSafe(file):
    if os.path.isfile(file):
        os.remove(file)

def getEncoding(file):
    test = open(file, "r")
    bom = test.read(2)
    if bom == codecs.BOM_LE:
        return "utf-16le"
    elif bom == codecs.BOM_BE:
        return "utf-16be"
    elif bom == codecs.BOM_UTF8:
        return "utf-8"
    else:
        return test.encoding
    test.close()

def printTraceback(info = ""):
    import traceback
    traceback.print_exc()
    print info

def findIgnStr(stri, search = str, start = 0):
    pos = 1
    while pos != -1:
        pos = stri.find(search, start)
        posLeft = stri.find("\"", start)
        posRight = stri.find("\"", pos + len(search))
        #print "[%d][%d][%d]" % (posLeft, pos, posRight)
        if posLeft < pos < posRight:
            start = posRight + 1
        else:
            return pos
    return -1

def isVarChar(stri = str, index = int):
    return index < len(stri) and (stri[index].isalnum() or stri == "_")
    
def findFirstWhitespace(stri = str):
    pos = stri.find(" ")
    pos2 = stri.find("\t")
    if pos2 == -1 or pos < pos2:
        return pos
    else:
        return pos2

def getParameter(stri = str, index = int, separator = ","):
    pos = findFirstWhitespace(stri)
    posBracket = stri.find("(")
    if posBracket == -1 or pos < posBracket:
        pass
    else:
        pos = posBracket
    
    return stri[pos+1:].split(separator)[index].strip()

def startswith(stri = str, prefix = str):
    stri = stri.lower()
    prefix = prefix.lower()
    return stri.startswith(prefix) and (len(prefix) == len(stri) or stri[len(prefix)].isspace())

def startswith2(stri = str, prefix = str):
    stri = stri.lower()
    prefix = prefix.lower()
    return stri.startswith(prefix) and (len(prefix) == len(stri) or not isVarChar(stri[len(prefix)]))

def isHeaderLine(line):
    return startswith(line, "Strict") or startswith(line, "SuperStrict") or startswith(line, "Import") or startswith(line, "Framework")

def fixPath(stri):
    return stri.replace("\\", "/")

def fixPathWindows(stri):
    return stri.replace("/", "\\")

def stripExt(stri):
    pos = stri.rfind(".")
    if pos != -1:
        return stri[:pos]
    return stri

def getCleanName(stri):
    result = ""
    for char in stri:
        if char.isalnum():
            result += char
    return result

def stripAll(path):
    return stripExt(os.path.basename(path))

#def fromStr(stri, fromStri):
#    return stri[stri.find(fromStri):]
